<?php
namespace adminmatrix\migration\command\seed;
use adminmatrix\migration\command\Seed;
use think\console\Input;
use think\console\input\Argument as InputArgument;
use think\console\input\Option as InputOption;
use think\console\Output;
use Phinx\Util\Util;
class Create extends Seed
{
    protected function configure()
    {
        $this->setName('seed:create')
            ->addOption('app' , '-a', InputOption::VALUE_OPTIONAL , '要创建的app应用名')
            ->setDescription('创建新的数据库插入数据')
            ->addArgument('name', InputArgument::REQUIRED, '要执行创建插入的文件名')
            ->setHelp(sprintf('%s创建新的数据库插入%s', PHP_EOL, PHP_EOL));
        $this->addOption('connection', 'c', InputOption::VALUE_REQUIRED, 'The database connection to use.');
    }

    protected function execute(Input $input, Output $output)
    {
        $appName = $this->appName = $input->getOption('app');
//        return parent::execute($input, $output); // TODO: Change the autogenerated stub
        $path = $this->getPath();
        if (!file_exists($path)) {
            mkdir($path, 0755, true);
        }
        $this->verifyMigrationDirectory($path);

        $path = realpath($path);

        $className = $input->getArgument('name');

        if (!Util::isValidPhinxClassName($className)) {
            throw new \InvalidArgumentException(sprintf('The seed class name "%s" is invalid. Please use CamelCase format', $className));
        }

        $filePath = $path . DIRECTORY_SEPARATOR . $className . '.php';

        if (is_file($filePath)) {
            throw new \InvalidArgumentException(sprintf('The file "%s" already exists', basename($filePath)));
        }



        // inject the class names appropriate to this seeder
        $contents = file_get_contents($this->getTemplate());
        $classes  = [
            'SeederClass' => $className,
        ];
        $contents = strtr($contents, $classes);

        if (false === file_put_contents($filePath, $contents)) {
            throw new \RuntimeException(sprintf('The file "%s" could not be written to', $path));
        }

        $output->writeln('<info>created</info> .' . str_replace(getcwd(), '', $filePath));
    }

    protected function getTemplate()
    {
        return __DIR__ . '/../stubs/seed.stub';
    }
}